/*
 * This file is part of quickReminder, a software for gamers
 *
 * Copyright (C) 2006-2009 Lucas Romero
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HRT;
using System.IO;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Collections.Specialized;
using Settings = GlobalSettings.Properties.Settings;

namespace quickReminder
{
    public partial class AequitasBenchmark : Form
    {
        public AequitasBenchmark()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StopWatch watch = new StopWatch();
            long elapsed, avg1=0, avg2=0;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (string.Compare(Path.GetPathRoot(openFileDialog1.FileNames[0]), Path.GetPathRoot(Settings.Default.AequitasPath), true) != 0)
                {
                    MessageBox.Show("In order to get correct results you need to select files that are on the same drive as aequitas!");
                    return;
                }
                for (int loop = 0; loop < 5; loop++ )
                    foreach (string s in openFileDialog1.FileNames)
                    {
                        ImageCodecInfo myImageCodecInfo;
                        System.Drawing.Imaging.Encoder myEncoder;
                        EncoderParameter myEncoderParameter;
                        EncoderParameters myEncoderParameters;


                        // Get an ImageCodecInfo object that represents the JPEG codec.
                        myImageCodecInfo = GetEncoderInfo("image/jpeg");

                        // Create an Encoder object based on the GUID

                        // for the Quality parameter category.
                        myEncoder = System.Drawing.Imaging.Encoder.Quality;

                        // Create an EncoderParameters object.

                        // An EncoderParameters object has an array of EncoderParameter

                        // objects. In this case, there is only one

                        // EncoderParameter object in the array.
                        myEncoderParameters = new EncoderParameters(1);

                        // Save the bitmap as a JPEG file with quality level 25.
                        myEncoderParameter = new EncoderParameter(myEncoder, 100L);
                        myEncoderParameters.Param[0] = myEncoderParameter;
                        ListViewItem i = new ListViewItem(Path.GetFileName(s));
                        using (Stream str = File.OpenRead(s))
                        {
                            Image img = Image.FromStream(str);
                            string file = Path.GetRandomFileName();

                            watch.Reset();
                            img.Save(file, myImageCodecInfo, myEncoderParameters);
                            elapsed = watch.Peek();
                            avg1 += elapsed;
                            i.SubItems.Add(elapsed / 10 + "ms");
                            File.Delete(file);

                            watch.Reset();
                            img.Save(file);
                            elapsed = watch.Peek();
                            avg2 += elapsed;
                            File.Delete(file);
                            i.SubItems.Add(elapsed / 10 + "ms");
                        }
                        listView1.Items.Add(i);
                        Application.DoEvents();
                    }
            }
            StringCollection drives = new StringCollection();
            drives.Add(Path.GetPathRoot(Settings.Default.AequitasPath));
            //drives.Add("c:");

            foreach (string drive in drives)
            {
                ProcessStartInfo info = new ProcessStartInfo("defrag", drive + " -a");
                //info.StandardOutputEncoding = Application.
                info.RedirectStandardOutput = true;
                info.CreateNoWindow = true;
                info.RedirectStandardError = true;
                info.UseShellExecute = false;
                info.ErrorDialog = true;
                info.ErrorDialogParentHandle = this.Handle;
                Process p = new Process();

                p.StartInfo = info;
                p.Start();
                p.WaitForExit();
                //MessageBox.Show()
                textBox1.AppendText(p.StandardOutput.ReadToEnd());
                //MessageBox.Show(p.StandardOutput.ReadToEnd());
            }
            MessageBox.Show(String.Format("Average with JPG compression: {0}ms\r\nAverage without JPG compression: {1}ms\r\n\r\nRecommended setting: {2}", avg1 / (listView1.Items.Count * 10), avg2 / (listView1.Items.Count * 10), avg1 > avg2 ? "OFF" : "ON"));
        }

        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

        private void AequitasBenchmark_Shown(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Settings.Default.AequitasPath))
            {
                MessageBox.Show(
                    "You must have had aequitas running at least one time during a match\r\nor used the AequitasInspector once, so that quickReminder knows where to find aequitas");
                this.Close();
            }

        }
    }
}